package com.envy.customizekaptcha.provider;

import com.envy.customizekaptcha.details.MyWebAuthenticationDetails;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class MyAuthenticationProvider extends DaoAuthenticationProvider {
    //自定义认证逻辑
//    @Override
//    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        //获取当前请求
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        //获取当前响应
//        //HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//
//        //获取用户通过表单输入的验证码字符串
//        String formCaptcha =request.getParameter("code");
//        //获取生成的验证码字符串（从session中获取)
//        String genCaptcha = (String) request.getSession().getAttribute("verify_code");
//
//        if(formCaptcha ==null || genCaptcha ==null || !formCaptcha.equals(genCaptcha)){
//            throw new AuthenticationServiceException("验证码错误!");
//        }
//        super.additionalAuthenticationChecks(userDetails, authentication);
//    }

    //获取登录额外信息
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if(!((MyWebAuthenticationDetails)authentication.getDetails()).isPassed()){
            throw new AuthenticationServiceException("验证码错误!");
        }
        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}
